const path = require("path")
const exceljs = require("exceljs")
const request = require("request")
const cheerio = require("cheerio")

const searchKey = "净利润(扣除非经常性损益后)(万元)"
const crawlUrl = "http://quotes.money.163.com/f10/zycwzb_600519.html#01c01"

const getBody = () =>
  new Promise((resolve, reject) => {
    request(crawlUrl, (err, res, body) => {
      if (err || res.statusCode !== 200) reject(err || `请检查网络，statusCode:${res.statusCode}`)
      resolve(body)
    })
  })

const getData = ($, el) => (index) => {
  const data = []
  el.eq(index)
    .children()
    .each(function () {
      data.push($(this).text())
    })
  return data
}

const insertExecl = (columns, data) => {
  let workbook = new exceljs.Workbook()
  workbook.created = new Date()
  workbook.modified = new Date()
  workbook.creator = "chenwl"
  workbook.lastModifiedBy = "chenwl"
  
  let writeNam = `${searchKey}.xlsx`;
  let sheet = workbook.addWorksheet("searchKey")
  sheet.columns = columns
  sheet.addRows(data)

  workbook.xlsx.writeFile(path.join(__dirname, writeNam)).then(() => {
    console.log("数据写入完毕 => %s", writeNam)
  })
}

;(async () => {
  const body = await getBody()
  const $ = cheerio.load(body)
  const index = $(`td:contains('${searchKey}')`).parent().index()
  const $elTr = $(".scr_table tr")
  const loadData = getData($, $elTr)

  // 日期
  let dates = loadData(0)
  // 数据
  let data = loadData(index + 1)

  const insertData = dates.map((date, i) => ({ date, name: data[i] }))
  const columns = [
    { header: "日期", key: "date", width: 20 },
    { header: searchKey, key: "name", with: 120 },
  ]

  insertExecl(columns, insertData);

})()
